const { contextBridge, ipcRenderer, shell } = require('electron')
const fs = require('fs');
const path = require('path')
const fileTool = require('../tool/file')

const exec = require('child_process').exec;

const dir7z = path.join(__dirname, '../../7zip/7z.exe')
const dirKtool = path.join(__dirname, '../../ktools-4.4.4/krane.exe')

contextBridge.exposeInMainWorld('electronAPI', {
  openSearchWin: (rs) => ipcRenderer.invoke('openSearchWin', rs),
  selectFile: (rs) => ipcRenderer.invoke('selectFile', rs),
  getConfig: (rs) => ipcRenderer.invoke('getConfig', rs),
  unzip: (zipFiles, outDir) => {

    zipFiles = JSON.parse(zipFiles)
   
    let unzipPath = outDir + "/unizp/"
    if (!fs.existsSync(unzipPath)) {
      fs.mkdirSync(unzipPath)
    }
 
  
    return new Promise((resolve, reject) => {
      let num = 0
      zipFiles.map(full_zipfile=>{
        let fileName = path.basename(full_zipfile, '.zip');
        let itemUnzipPath = unzipPath + fileName
        if (!fs.existsSync(itemUnzipPath)) {
          fs.mkdirSync(itemUnzipPath)
        }

        let itemExpPath = outDir + "/" + fileName
        if (fs.existsSync(itemExpPath)) {
          fileTool.clearDir(itemExpPath)
        } else {
          fs.mkdirSync(itemExpPath)
        }

        let cmd = `${dir7z} x "${full_zipfile}" -o"${itemUnzipPath}" -y`;
        console.log(cmd)
        exec(cmd, function(error, stdout, stderr) {

          let cmd = `${dirKtool} "${itemUnzipPath}" "${itemExpPath}"`
          console.log(cmd)
          exec(cmd, function(error, stdout, stderr) {
            num ++
            if(num >= zipFiles.length) {
              resolve('成功') // 数据处理完成
            }
          })
        
        });
      })
    })
  },
  openDir: (dir)=>{
    shell.openPath(dir)
  },
  pwd:()=>{
    return __dirname;
  },
  serverUpdate: (indir, outdir, cover) => ipcRenderer.invoke('setMod', indir, outdir, cover),

  onNameUpdate: (callback) => ipcRenderer.on('name-update', (_event, value) => callback(value))
})
